package com.trs.publish.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.trs.publish.domain.Power;
import com.trs.publish.repository.PowerRepository;



/**
 * @author jia.haihong
 */
@Service
@Transactional
public class PowerService{

	@Autowired
    private PowerRepository powerRepository;

	public List<Power> getPowers(Long roleId) {
		return powerRepository.findPowers(roleId);
	}

	public List<Power> getPowersByRoleNames(List<String> roleNameList) {
		List<Power> list = new ArrayList<Power>();
		if(roleNameList != null && roleNameList.size()>0){
			list = powerRepository.findPowersByRoles(roleNameList);
		}
		return list;
	}

	public List<Power> getList(Power power) {
		return powerRepository.findByPower(power);
	}

	public void deletePower(long id) {
		powerRepository.deleteById(id);
	}

	public Power findById(long id) {
		return powerRepository.findById(id);
	}

	public void save(Power power) {
		powerRepository.save(power);
	}

	public void update(Power power) {
		powerRepository.update(power);
	}

	/**
	 * 权限排序，相同分类下的权限聚在一起
	 * @param powers 权限列表
	 * @return 排序后的权限列表
	 */
	public List<Power> rankPowers(List<Power> powers){
		if (powers == null || powers.size()<=0) {
			return powers;
		}
		
		//排序 根据权限优先级、一级分类、二级分类 排序
		Collections.sort(powers, new Comparator<Power>() {   
		    public int compare(Power o1, Power o2) { 
		    	if (o1.getRank() != o2.getRank()) {
		    		return (int) (o1.getRank() - o2.getRank());
				}
				if (o1.getCatalog1()!=o2.getCatalog1()) {
					return (int) (o1.getCatalog1() - o2.getCatalog1());
				}
				if (o1.getCatalog2()!=o2.getCatalog2()) {
					return (int) (o1.getCatalog2() - o2.getCatalog2());
				}
		    	return (int) (o1.getRank() - o2.getRank());
		    }
		}); 
		
		return powers;
	}

}
